package com.qut.graduate.busrtquery;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.search.busline.BusLineResult;
import com.baidu.mapapi.search.busline.OnGetBusLineSearchResultListener;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.context.IconicsContextWrapper;
import com.mikepenz.iconics.typeface.IIcon;

import java.io.File;
import java.util.ArrayList;

import com.qut.graduate.busrtquery.interfaces.HttpCallback;
import com.qut.graduate.busrtquery.interfaces.LocationChangeCallBack;
import com.qut.graduate.busrtquery.service.MyLocationService;
import com.qut.graduate.busrtquery.utils.common.LogUtils;
import com.qut.graduate.busrtquery.utils.uiabout.ColorPaletteUtils;
import com.qut.graduate.busrtquery.utils.store.SPUtils;
import com.qut.graduate.busrtquery.utils.uiabout.ThemeUtils;
import com.qut.graduate.busrtquery.utils.uiabout.ToastColorfulUtils;

/**
 * @Author WLL
 * @Time: 2019/3/18 20:40
 */
public class BaseActivity extends AppCompatActivity implements LocationChangeCallBack, OnGetGeoCoderResultListener,
        OnGetRoutePlanResultListener, OnGetPoiSearchResultListener, OnGetBusLineSearchResultListener, HttpCallback {
    private static final String TAG = "BaseActivity";
    private MyLocationService.MyBind bind; // 定位服务
    protected Activity mContext;
    private ArrayList<Fragment> mFragmentList = new ArrayList<>();
    // 显示哪个Fragment，默认显示第一页（设置）
    protected int mFragmentShowNow = 0;
    private int mFragmentUiLayout = 0;
    private ThemeUtils themeUtils;
    protected SPUtils preferenceUtils;
    private boolean coloredNavBar;
    private boolean obscuredStatusBar;
    private boolean applyThemeImgAct;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onPreCreate();
        setContentView(getLayoutId());
        init();
    }

    protected void onPreCreate() {
        this.mContext = this;
        preferenceUtils = SPUtils.getInstance(getApplicationContext());
        themeUtils = new ThemeUtils(getApplicationContext());
    }

    protected int getLayoutId() {
        return 0;
    }

    protected void init() {
        location();
    }

    /**
     * 绑定service，实现定位
     */
    private void location() {
        Intent intent = new Intent(this, MyLocationService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    protected ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder myBind) {
            bind = (MyLocationService.MyBind) myBind;
            bind.getMyLocationService().setmLocationChangeCallBack(BaseActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    /**
     * 定位改变回调，在需要的activity中重写该方法
     *
     * @param bdLocation
     */
    @Override
    public void onLocationChange(BDLocation bdLocation) {

    }

    // 当Activity回调onRestart时（从上一个页面返回），检查当前主题是否已将被更改。
    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateTheme();
        initResume();
    }

    public void updateTheme() {
        themeUtils.updateTheme();
        coloredNavBar = preferenceUtils.getBoolean(getString(R.string.preference_colored_nav_bar), false);
        obscuredStatusBar = preferenceUtils.getBoolean(getString(R.string.preference_translucent_status_bar), true);
        applyThemeImgAct = preferenceUtils.getBoolean(getString(R.string.preference_apply_theme_pager), true);
    }

    public void updateBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (isTranslucentStatusBar()) {
                getWindow().setStatusBarColor(ColorPaletteUtils.getObscuredColor(getPrimaryColor()));
            } else {
                getWindow().setStatusBarColor(getPrimaryColor());
            }
            getWindow().setNavigationBarColor(isNavigationBarColored() ? getPrimaryColor() :
                    ContextCompat.getColor(getApplicationContext(), R.color.md_black_1000));
        }
    }

    public void initResume() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (transaction.isEmpty() && mFragmentList.size() > 0) {
            for (int i = 0; i < mFragmentList.size(); i++) {
                if (null != mFragmentList.get(i) && !mFragmentList.get(i).isAdded() &&
                        null == fragmentManager.findFragmentByTag(i + "")) {
                    transaction.add(mFragmentUiLayout, mFragmentList.get(i), i + "");
                }
            }
        }
        for (int i = 0; i < mFragmentList.size(); i++) {
            transaction.hide(mFragmentList.get(i));
        }
        if (mFragmentList.size() > 0) transaction.show(mFragmentList.get(mFragmentShowNow));
        transaction.commit();
    }

    /**
     * 必须在子Activity的onCreate调用，否则就啥都没有
     *
     * @param fragmentList
     * @param uiLayout     布局类型R.id.fragmentLayout
     */
    public void initBRTQuery(ArrayList<Fragment> fragmentList, int uiLayout) {
        mFragmentShowNow = 0;
        this.mFragmentUiLayout = uiLayout;
        this.mFragmentList = fragmentList;
    }

    public void showFragment(int fragmentId) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (null != mFragmentList.get(mFragmentShowNow) && null != mFragmentList.get(fragmentId)) {
            transaction.hide(mFragmentList.get(mFragmentShowNow));
            transaction.show(mFragmentList.get(fragmentId));
            mFragmentShowNow = fragmentId;
        } else {
            mFragmentShowNow = 0; // 预防错误情况
        }
        transaction.commit();
    }

    /*--------------网络请求及下载，在需要的子类activity中实现--------------*/

    @Override
    public void onHttpSuccess(String json, int tag) {
    }

    @Override
    public void onHttpFailed(String errorMsg, int tag) {
    }

    @Override
    public void onDownloadSuccess(File file) {
    }

    @Override
    public void onDownloading(int progress) {
    }

    @Override
    public void onDownloadFailed(Exception e) {
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
        if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            ToastColorfulUtils.error("抱歉，未能找到结果");
            return;
        }
        @SuppressLint("DefaultLocale")
        String strInfo = String.format("纬度：%f 经度：%f", geoCodeResult.getLocation().latitude,
                geoCodeResult.getLocation().longitude);
        ToastColorfulUtils.info(strInfo);
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            LogUtils.d("----ReverseGeoCode  抱歉，未能找到结果", this.getClass());
            return;
        }
        LogUtils.d("----ReverseGeoCode  地址编码结果: " + reverseGeoCodeResult.getAddress(), this.getClass());
    }

    @Override
    public void onGetBusLineResult(BusLineResult busLineResult) {

    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {

    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(IconicsContextWrapper.wrap(newBase));
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void setNavBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (isNavigationBarColored()) getWindow().setNavigationBarColor(getPrimaryColor());
            else
                getWindow().setNavigationBarColor(ContextCompat.getColor(getApplicationContext(), R.color.md_black_1000));
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    protected void setStatusBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (isTranslucentStatusBar())
                getWindow().setStatusBarColor(ColorPaletteUtils.getObscuredColor(getPrimaryColor()));
            else
                getWindow().setStatusBarColor(getPrimaryColor());
        }
    }

    public int getPrimaryColor() {
        return themeUtils.getPrimaryColor();
    }

    public int getmWindowBackgroundColor() {
        return themeUtils.getmWindowBackgroundColor();
    }

    public int getAccentColor() {
        return themeUtils.getAccentColor();
    }

    public boolean isNavigationBarColored() {
        return coloredNavBar;
    }

    public boolean isTranslucentStatusBar() {
        return obscuredStatusBar;
    }

    protected int getBackgroundColor() {
        return themeUtils.getBackgroundColor();
    }

    public int getTextColor() {
        return themeUtils.getTextColor();
    }

    public int getCardBackgroundColor() {
        return themeUtils.getCardBackgroundColor();
    }

    public int getDialogStyle() {
        return themeUtils.getDialogStyle();
    }

    protected int getPopupToolbarStyle() {
        return themeUtils.getPopupToolbarStyle();
    }

    public void updateSwitchColor(SwitchCompat sw, int color) {
        themeUtils.updateSwitchColor(sw, color);
    }

    public IconicsDrawable getToolbarIcon(IIcon icon) {
        return themeUtils.getToolbarIcon(icon);
    }

}
